<template>
  <div class="app-container">
    <el-card>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="个人资料" name="personal">
          <div class="doctor-info">
            <div class="avatar-section">
              <el-upload
                  class="avatar-uploader"
                  action="/api/doctor/upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  accept="image/jpeg,image/png,image/jpg"
              >
                <el-image
                    v-if="doctorInfo.imgurl"
                    :src="doctorInfo.imgurl"
                    class="avatar"
                    fit="cover"
                    style="width: 100px; height: 100px; border-radius: 50%"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                  <template #placeholder>
                    <div class="image-slot">
                      <el-icon><Loading /></el-icon>
                    </div>
                  </template>
                </el-image>
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </div>

            <div class="info-form">
              <el-form
                  ref="formRef"
                  :model="doctorInfo"
                  :rules="rules"
                  label-width="100px"
                  class="doctor-form"
              >
                <el-form-item label="姓名：" prop="name">
                  <el-input v-model="doctorInfo.name"  disabled="disabled"/>
                </el-form-item>

                <el-form-item label="医院：" prop="hospital">
                  <el-select v-model="doctorInfo.hospitall.name" placeholder="请选择医院" disabled>
                    <el-option
                        :label="doctorInfo.hospitall.name"
                        :value="doctorInfo.hospitall.name"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="性别：" prop="gender">
                  <el-radio-group v-model="doctorInfo.gender" disabled>
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="2">女</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="手机号：" prop="phone">
                  <el-input v-model="doctorInfo.phone" maxlength="11" />
                </el-form-item>

                <el-form-item label="科室：" prop="department">
                  <el-select v-model="doctorInfo.bigdep.name" placeholder="请选择科室" disabled>
                    <el-option
                        :label="doctorInfo.bigdep.name"
                        :value="doctorInfo.bigdep.name"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="职称：" prop="title">
                  <el-select v-model="doctorInfo.title" placeholder="请选择职称">
                    <el-option label="主任" value="主任" />
                    <el-option label="副主任" value="副主任" />
                    <el-option label="医师" value="医师" />
                  </el-select>
                </el-form-item>
                <el-form-item label="问诊价格：" prop="price">
                  <el-input-number v-model="doctorInfo.price" :min="1" :max="1000">
                    <template #prefix>
                      <span>￥</span>
                    </template>
                  </el-input-number>
                </el-form-item>
                <el-form-item label="个人简介：" prop="introduction">
                  <el-input
                      v-model="doctorInfo.desc"
                      type="textarea"
                      :rows="4"
                      placeholder="请输入个人简介..."
                      maxlength="300"
                      show-word-limit
                  />
                </el-form-item>
              </el-form>
            </div>
            <el-button type="primary" @click="updateDocrorsxx">更改信息</el-button>
          </div>
        </el-tab-pane>

        <!--        <el-tab-pane label="资质信息" name="qualification">-->
        <!--          <div class="qr-code">-->
        <!--            <span class="qr-label">二维码：</span>-->
        <!--            <div class="qr-image">-->
        <!--              <el-image-->
        <!--                  :src="doctorInfo.qrCode || defaultQR"-->
        <!--                  fit="cover"-->
        <!--                  class="qr"-->
        <!--              >-->
        <!--                <template #error>-->
        <!--                  <div class="image-slot">-->
        <!--                    <el-icon><Picture /></el-icon>-->
        <!--                  </div>-->
        <!--                </template>-->
        <!--              </el-image>-->
        <!--            </div>-->
        <!--            <el-upload-->
        <!--                class="qr-uploader"-->
        <!--                action="/api/upload"-->
        <!--                :show-file-list="false"-->
        <!--                :on-success="handleQRSuccess"-->
        <!--            >-->
        <!--              <el-button size="small" type="primary">下载二维码</el-button>-->
        <!--            </el-upload>-->
        <!--          </div>-->
        <!--        </el-tab-pane>-->

        <!--        <el-tab-pane label="患教内容" name="education">-->
        <!--          &lt;!&ndash; 患教内容标签页的内容 &ndash;&gt;-->
        <!--          患教内容-->
        <!--        </el-tab-pane>-->

        <el-tab-pane label="患者信息" name="patients">
          <el-table
              :data="patientList"
              @selection-change="handleSelectionChange"
              style="width: 100%"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="患者编号" align="center" prop="id" />
            <el-table-column label="患者姓名" align="center" prop="name" />
            <el-table-column label="联系电话" align="center" prop="phoneNumber" />
            <el-table-column label="性别" align="center" prop="gender">
              <template #default="{ row }">
                {{ row.gender === 1 ? '男' : '女' }}
              </template>
            </el-table-column>
            <el-table-column label="医嘱" align="center" prop="remarks" />
            <el-table-column label="患者状态" align="center" prop="recoveryStatus">
              <template #default="{ row }">
                <el-tag :type="row.recoveryStatus === '1' ? 'success' : 'info'">
                  {{ row.recoveryStatus === '1' ? '已康复' : '治疗中' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <!-- 患者信息标签页的内容 -->
        </el-tab-pane>

        <el-tab-pane label="患者评价" name="reviews">
          <!-- 患者评价标签页的内容 -->
          <el-table
              :data="evaluationlist"
              @selection-change="handleSelectionChange"
              style="width: 100%"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="患者编号" align="center" prop="id" />
            <el-table-column label="患者姓名" align="center" prop="patientInfo.name" />
            <el-table-column label="联系电话" align="center" prop="mobileNumber" />
            <el-table-column label="评价" align="center" prop="rating">
              <template #default="{ row }">
                <el-rate
                    v-model="row.rating"
                    disabled
                    show-score
                    text-color="#ff9900"
                    score-template="{value}"
                />
              </template>
            </el-table-column>
            <el-table-column label="评价内容" align="center" prop="evaluationContent"/>
            <el-table-column label="评价时间" align="center" prop="evaluationTime" />
          </el-table>
        </el-tab-pane>

        <!--        <el-tab-pane label="门诊时间" name="schedule">-->
        <!--          &lt;!&ndash; 门诊时间标签页的内容 &ndash;&gt;-->
        <!--        </el-tab-pane>-->
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { Picture } from '@element-plus/icons-vue'
import { getDoctors, PatientBydoctorId, updateDoctors,Patienevaluation } from '../../api/doctors/doctors.js'
import { ElMessage } from 'element-plus'

// 添加活动标签页变量，并设置默认值为 'personal'
const activeTab = ref('personal')

const route = useRoute()

const doctorInfo = ref({
  id: null,
  name: '',
  hospitall: {
    id: null,
    name: ''
  },
  gender: 1,
  phone: '',
  bigdep: {
    id: null,
    name: ''
  },
  title: '',
  price: 0,
  desc: '',
  imgurl: '',
  expertise: '',
  introduction: '',
  experience: '',
  avatar: '',
  qrCode: ''
})
/**
 * 患者信息
 */
const patientList=ref([])
const getPatientList = async () => {
  try {
    const doctorId = route.params.id
    const res = await PatientBydoctorId(doctorId)
    console.log(res)
    patientList.value = res.data
  } catch (error) {
    console.error('获取患者信息失败:', error)
    ElMessage.error('获取患者信息失败')
  }
}
/**
 * 患者评价
 * @returns {Promise<void>}
 */
const evaluationlist=ref([])
const getEvaluation = async () => {
  try {
    const doctorId = route.params.id
    const res = await Patienevaluation(doctorId)
    console.log(res)
    evaluationlist.value = res.data
  } catch (error) {
    console.error('获取医生评价失败:', error)
    ElMessage.error('获取医生评价失败')
  }
}

// 获取医生信息
const getDoctorInfo = async () => {
  try {
    const id = route.params.id
    const res = await getDoctors(id)
    console.log('医生信息API响应:', res)
    if (res && res.data) {
      doctorInfo.value = res.data
      console.log('设置后的医生信息:', doctorInfo.value)
    } else {
      ElMessage.warning('未获取到医生信息')
    }
  } catch (error) {
    console.error('获取医生信息失败:', error)
    ElMessage.error('获取医生信息失败')
  }
}
const imageUrl = ref('')

// 头像上传成功
const handleAvatarSuccess = (
    response,
    uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  doctorInfo.value.imgurl=response.data
  console.log(response);
}
//验证的函数
const beforeAvatarUpload = (rawFile) => {
  const isImage = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png' || rawFile.type === 'image/jpg';
  if (!isImage) {
    ElMessage.error('Avatar picture must be in JPG, PNG, or JPEG format!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size cannot exceed 2MB!');
    return false;
  }
  return true;
}

// 添加表单校验规则
const rules = reactive({
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号码', trigger: 'blur' }
  ],
  // 可以添加其他字段的校验规则
  name: [
    { required: true, message: '请输入医生姓名', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请选择职称', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入问诊价格', trigger: 'blur' }
  ]
})

// 修改更新函数，使用正确的表单引用方式
const formRef = ref(null) // 确保这个引用已经在顶部定义

const updateDocrorsxx = async () => {
  try {
    // 使用正确的表单引用进行验证
    if (!formRef.value) {
      ElMessage.warning('表单引用不存在')
      return
    }

    // 表单验证
    await formRef.value.validate()

    // 验证通过后提交数据
    const res = await updateDoctors(doctorInfo.value)
    if (res.flag === true) {
      ElMessage.success('更改信息成功')
      getDoctorInfo()
    } else {
      ElMessage.error(res.message || '更改信息失败')
    }
  } catch (error) {
    console.error('更改医生信息失败:', error)
    ElMessage.error('表单验证失败，请检查输入')
  }
}

// 二维码上传成功
const handleQRSuccess = (response) => {
  doctorInfo.value.qrCode = response.url
  ElMessage.success('二维码上传成功')
}
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

onMounted(() => {
  getDoctorInfo()
  getPatientList()
  getEvaluation()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.doctor-info {
  display: flex;
  gap: 40px;
  padding: 20px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.avatar-container {
  width: 200px;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.info-form {
  flex: 1;
}

.doctor-form {
  max-width: 600px;
}

.qr-code {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
}

.qr-label {
  font-size: 14px;
  color: #606266;
}

.qr-image {
  width: 150px;
  height: 150px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.qr {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

:deep(.el-tabs__nav) {
  background-color: #fff;
  padding: 0 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
